﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Net;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using MatrixWebApiCore.Common;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using MatrixWebApiCore.IDao;
using MatrixWebApiCore.Entity;
using MatrixWebApiCore.Common.Data;
using MatrixWebApiCore.Dao;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;

namespace MatrixWebApiCore.Filter
{
    public class ExceptionFilter : IExceptionFilter
    {
 
        public void OnException(ExceptionContext context)
        {
            MatrixWebApiCore.Entity.BackResult<object> data = new MatrixWebApiCore.Entity.BackResult<object>
            {
                Success = false
            };
            if (context.Exception is OutMsgException)
            {
                //自定义提示消息
                data.Msg = context.Exception.Message;
                //context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
            }
            else
            {
                data.Msg = "500内部处理异常";
#if DEBUG
                data.Msg = context.Exception.ToString();
#endif
                Task.Run(() =>
                {
                    IServiceScope scope=null;                 
                    try
                    {
                        //请求的地址
                        string url = context.HttpContext.Request.Host.Value + context.HttpContext.Request.Path.Value;
                        if (context.Exception is WebException)
                        {
                            url = ((System.Net.HttpWebResponse)((System.Net.WebException)context.Exception).Response).ResponseUri.AbsoluteUri;
                        }
                        IWebHost host = Program.BuildWebHost(null);                   
                        scope = host.Services.CreateScope();
                        ILogRepository _logRepository = scope.ServiceProvider.GetService<ILogRepository>();
                        DataContext _dataContext = scope.ServiceProvider.GetService<DataContext>();                        

                        Log log = new Log();
                        log.Id = Guid.NewGuid();
                        log.RequestURL = url;
                        log.LogTxt = context.Exception.ToString();
                        log.CreateTime = DateTime.Now;                      
                        _logRepository.Add(log);
                        try
                        {
                            //删除较老日志记录
                            //DateTime dateTime = DateTime.Now.AddDays(-5).Date;
                            //logRepository.Delete(w => w.CreateTime.Date < dateTime);
                            string dateTime = DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd");
                            int count = _dataContext.Database.ExecuteSqlCommand("delete from Log where  CONVERT(varchar(30), CreateTime, 23)<@date", new SqlParameter("date", dateTime));
                            MessageHelper.LogInfo($"删除了日志记录{count}条");
                        }
                        catch (Exception ex)
                        {
                            MessageHelper.LogErrorInfo("删除数据库日志记录异常", ex);
                        }                     
                    }
                    catch (Exception ex)
                    {
                        MessageHelper.LogErrorInfo("记录日志到数据库异常", ex);
                    }
                    finally
                    {                      
                        scope.Dispose();
                    }
                });
                //记录异常日志
                MessageHelper.LogErrorInfo("处理异常", context.Exception);
            }
            JsonResult result = new JsonResult(data);
            context.Result = result;
            context.ExceptionHandled = true;
        }

    }
}